package com.xiaozhen.blog.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.code.kaptcha.Producer;
import com.xiaozhen.blog.entity.User;
import com.xiaozhen.blog.service.UserService;
import com.xiaozhen.blog.utils.RedisKeyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.xiaozhen.blog.utils.CommunityConstant.*;

/**
 * @create 2023-04-23 15:32
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点击导航栏 注册 按钮
     *
     * @return
     */
    @GetMapping("/register")
    public String getRegister() {
        return "register";
    }

    /**
     * 点击注册页面 注册 按钮
     *
     * @param model
     * @param user
     * @return
     */
    @PostMapping("/register")
    public String register(Model model, User user) {
        // TODO 报错
        Map<String, Object> map = userService.register(user);
        // 如果 map 为null,则说明注册成功
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活！");
            model.addAttribute("target", "/");
            return "operate";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "register";
        }
    }

    /**
     * 点击注册页面 注册 按钮之后返回的页面
     *
     * @param userId
     * @param code
     * @param model
     * @return
     */
    // http://localhost:8081/blog/activation/用户id/激活码
    @GetMapping("/activation/{userId}/{code}")
    public String activation(@PathVariable Long userId,
                             @PathVariable String code,
                             Model model) {
        int activation = userService.activation(userId, code);
        if (activation == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功，您的账号已经可以正常使用了！");
            model.addAttribute("target", "/login");
        } else if (activation == ACTIVATION_REFEAT) {
            model.addAttribute("msg", "无效操作，该账号已经激活过了！");
            model.addAttribute("target", "/");
        } else {
            model.addAttribute("msg", "激活失败，您提供的激活码不正确！");
            model.addAttribute("target", "/");
        }
        return "operate";
    }

    /**
     * 点击导航栏 登录 按钮
     *
     * @return
     */
    @GetMapping("/login")
    public String getLogin() {
        return "login";
    }

    /**
     * 点击登录页面 登录 按钮
     *
     * @param username
     * @param password
     * @param code
     * @param remeberme
     * @param model
     * @param response
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password, String code, boolean remeberme,
                        Model model, HttpServletResponse response, @CookieValue("kaptchaOwner") String kaptchaOwner) {
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)) {
            // 从 redis 中获取验证码
            String redisKey = RedisKeyUtils.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }


        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确！");
            return "/login";
        }
        // 检查账号，密码
        // 判断超时时间
        int expiredSecinds = remeberme ? REMEMBER_EXPIRED_SECONDE : DEFAULT_EXPIRED_SECONDE;
        Map<String, Object> map = userService.login(username, password, expiredSecinds);
        // TODO
        if (map.containsKey("token")){
            Cookie cookie = new Cookie("token", map.get("token").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSecinds);
            response.addCookie(cookie);
            return "redirect:/";
        }else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/login";
        }
    }

    /**
     * 返回验证码图片
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, Long expiredSeconds) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        // 生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);
        // 验证码的归属
        String kaptchaOwner = SecureUtil.simpleUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60); // 生效时间
        cookie.setPath(contextPath); // 路径
        response.addCookie(cookie);
        // 将验证码存入 redis
        String redisKey = RedisKeyUtils.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS);

        // 将图片输出给浏览器
        // 设置输出类型
        response.setContentType("/image/png");
        // 获取输出流
        try {
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            logger.error("响应验证码失败：" + e.getMessage());
        }
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @RequestMapping("/logoff")
    public String logout(@CookieValue("token") String token,HttpServletResponse response) {
        System.out.println("调用 logout");
        Cookie cookie = new Cookie("token", token);
        cookie.setPath(contextPath);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        userService.logout(token);
        return "redirect:/login";
    }
}
